<template>
  <div class="after-sales">
    <!-- 新增标签页切换 -->
    <!-- 一体式切换按钮 -->
    <div class="segmented-control">
      <button
          class="segmented-btn"
          :class="{ 'active': activeTab === 'pending' }"
          @click="activeTab = 'pending'"
      >
        待处理记录 ({{ pendingRecords.length }})
      </button>
      <button
          class="segmented-btn"
          :class="{ 'active': activeTab === 'history' }"
          @click="activeTab = 'history'"
      >
        售后历史 ({{ afterSalesHistory.length }})
      </button>
    </div>

    <!-- 待处理记录 -->
    <div v-if="activeTab === 'pending'" class="section">
        <!-- 原有表格结构保持不变 -->
        <div class="section">
          <h2>待处理记录</h2>
          <table class="table">
            <thead>
            <tr>
              <th>售后编号</th>
              <th>商品信息</th>
              <th>详情</th>
              <th>处理</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="record in pendingRecords" :key="record.id">
              <td>{{ record.id }}</td>
              <td class="product-info">
                <div class="product-details">
                  <span class="product-name">{{ record.productName }}</span>
                  <p class="product-desc">{{ record.productDescription }}</p>
<!--                  <span class="product-price">￥{{ record.price }}</span>-->
                </div>
                <img :src="record.productImage" alt="商品图片" class="product-image" />
              </td>
              <td><button @click="viewAfterSalesDetail(record)" class="btn">售后详情</button></td>
              <td>
                <button @click="handleAfterSales(record)" class="btn handle-btn">处理</button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>
    </div>

    <!-- 售后历史 -->
    <div v-if="activeTab === 'history'" class="section">
      <div class="section">
        <h2>售后历史</h2>
        <table class="table">
          <thead>
          <tr>
            <th>售后编号</th>
            <th>商品信息</th>
            <th>详情</th>
            <th>处理结果</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="record in afterSalesHistory" :key="record.id">
            <td>{{ record.id }}</td>
            <td class="product-info">
<!--              <img :src="record.productImage" alt="商品图片" class="product-image" />-->
              <div class="product-details">
                <span class="product-name">{{ record.productName }}</span>
                <p class="product-desc">{{ record.productDescription }}</p>
<!--                <span class="product-price">￥{{ record.price }}</span>-->
              </div>
              <img :src="record.productImage" alt="商品图片" class="product-image" />
            </td>
            <td><button @click="viewAfterSalesDetail(record)" class="btn">售后详情</button></td>
            <td>{{ record.result }}</td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div v-if="showDetails" class="modal">
      <div class="modal-content">
        <h3 class="modal-title">售后详情</h3>
        <div class="modal-body">
          <div class="detail-item">
            <strong>姓名:</strong> <span>{{ selectedRecord.name }}</span>
          </div>
          <div class="detail-item">
            <strong>电话:</strong> <span>{{ selectedRecord.phone }}</span>
          </div>
          <div class="detail-item">
            <strong>收货地址:</strong> <span>{{ selectedRecord.address }}</span>
          </div>
          <div class="detail-item">
            <strong>申请原因:</strong>
<!--            <p class="application-detail">{{ selectedRecord.applicationDetail }}</p>-->
            <p class="application-detail">{{ selectedRecord.productDescription }}</p>
          </div>
          <!-- 图片凭证 -->
          <div class="detail-item" v-if="selectedRecord.imageProof && selectedRecord.imageProof.length > 0">
            <strong>图片凭证:</strong>
            <div class="image-proof-grid">
              <div v-for="(image, index) in selectedRecord.imageProof" :key="index" class="image-proof-item">
                <img :src="image" alt="图片凭证" class="proof-image" />
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeDetails" class="btn close-btn">关闭</button>
        </div>
      </div>
    </div>

    <!-- 处理售后弹窗 -->
    <div v-if="showHandleModal" class="modal">
      <div class="modal-content">
        <h3>处理售后</h3>
        <select v-model="selectedHandleOption" class="select">
          <option value="退货">退货</option>
          <option value="退款">退款</option>
        </select>
        <button @click="processAfterSales" class="btn submit-btn">提交处理</button>
        <button @click="closeHandleModal" class="btn close-btn">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'; // 导入封装好的request

export default {
  data() {
    return {
      activeTab: 'pending', // 新增激活标签状态
      pendingRecords:[],
      afterSalesHistory: [],
      selectedRecord: null,
      showDetails: false,
      showHandleModal: false,
      selectedHandleOption: "",
      storeId:1
    };
  },
  mounted() {
    this.fetchPendingRecords();
    this.fetchAfterSalesHistory();
  },
  methods: {
    async fetchPendingRecords() {
      try {
        const res = await request({
          url: `/aftersale/pending/${this.storeId}`,
          method: 'get',
          params: {
            pageNum: 1,
            pageSize: 20
          }
        });

        if (res.code === "200") {
          const list = res.data?.list || [];
          this.pendingRecords = list.map(item => ({
            id: item.applicationId,
            orderId: item.orderId,
            productName: item.productTitle,
            productImage: item.productImages.split(',')[0] || '',
            productDescription: item.productDescription,
            price: '', // 后端暂未提供价格字段
            saleType: item.saleType,
            result: '',
            ...item
          }));
        }
      } catch (err) {
        console.error('获取待处理售后失败', err);
        this.$message.error('获取待处理售后失败');
      }
    },

    async fetchAfterSalesHistory() {
      try {
        const res = await request({
          url: `/aftersale/history/${this.storeId}`,
          method: 'get',
          params: {
            pageNum: 1,
            pageSize: 50
          }
        });

        if (res.code === "200") {
          const list = res.data?.list || [];
          this.afterSalesHistory = list.map(item => ({
            id: item.applicationId,
            orderId: item.orderId,
            productName: item.productTitle,
            productImage: item.productImages.split(',')[0] || '',
            productDescription: item.productDescription,
            price: '',
            saleType: item.saleType,
            result: item.resultType || '已处理',
            ...item
          }));
        }
      } catch (err) {
        console.error('获取售后历史失败', err);
        this.$message.error('获取售后历史失败');
      }
    },

    async viewAfterSalesDetail(record) {
      try {
        const res = await request({
          url: `/aftersale/detail/${record.id}`,
          method: 'get'
        });

        if (res.code === "200") {
          const data = res.data;
          this.selectedRecord = {
            id: data.applicationId,
            orderId: data.orderId,
            name: data.buyerName,
            phone: data.buyerPhone,
            address: data.buyerAddress,
            productName: data.productTitle,
            productDescription: data.productDescription,
            saleType: data.saleType,
            productImages: data.productImages, // 原始字符串
            imageProof: data.productImages ? data.productImages.split(',') : [],
            result: data.resultType || ''
          };
          this.showDetails = true;
        }
      } catch (err) {
        console.error('获取售后详情失败', err);
        this.$message.error('获取售后详情失败');
      }
    },

    closeDetails() {
      this.showDetails = false;
    },

    async processAfterSales() {
      if (!this.selectedHandleOption) {
        this.$message.warning("请选择处理结果");
        return;
      }

      const payload = {
        applicationId: this.selectedRecord.id,
        orderId: this.selectedRecord.orderId,
        productTitle: this.selectedRecord.productName,
        productDescription: this.selectedRecord.productDescription,
        productImages: this.selectedRecord.productImages || '',
        saleType: this.selectedRecord.saleType || '退货退款',
        resultType: this.selectedHandleOption  // "退货"或"退款"
      };

      try {
        const res = await request({
          url: '/aftersale/process',
          method: 'put',
          data: payload
        });

        if (res.code === "200") {
          this.$message.success("处理成功");
          this.showHandleModal = false;
          this.fetchPendingRecords();      // 刷新待处理列表
          this.fetchAfterSalesHistory();   // 刷新历史记录
        } else {
          this.$message.error("处理失败：" + res.msg);
        }
      } catch (err) {
        console.error('提交处理失败', err);
        this.$message.error("提交处理异常");
      }
    },

    // 处理售后
    handleAfterSales(record) {
      this.selectedRecord = record;
      this.selectedHandleOption = "";
      this.showHandleModal = true;
    },

    // 关闭处理售后弹窗
    closeHandleModal() {
      this.showHandleModal = false;
    },
  }
};
</script>

<style scoped>
.after-sales {
  font-family: 'Segoe UI', system-ui, sans-serif;
  margin: 2rem;
  background: linear-gradient(135deg, #f8f9fc 0%, #eef1f6 100%);
  border-radius: 1rem;
  padding: 2.5rem;
  box-shadow: 0 12px 24px rgba(0,51,102,0.08);
}

/* 一体式切换按钮 */
.segmented-control {
  display: flex;
  background: #f0f2f5;
  border-radius: 12px;
  overflow: hidden;
  width: 100%; /* 让按钮组和 section 对齐 */
  max-width: 1000px; /* 适应大屏，防止超出 */
  margin: 0 auto 1.5rem; /* 居中对齐，并且底部增加间距 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.segmented-btn {
  flex: 1;
  padding: 1rem;
  border: none;
  background: transparent;
  color: #7f8c9d;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
}

.segmented-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.segmented-btn.active {
  background: white;
  color: #0066cc;
  box-shadow: inset 0 -2px 0 #0066cc; /* 底部选中高亮 */
}

/* Section 样式调整 */
.section {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  max-width: 1000px; /* 统一最大宽度 */
  margin: 0 auto 2.5rem; /* 居中 & 设置底部间距 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.section:hover {
  transform: translateY(-2px);
}

h2 {
  color: #2c3e50;
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
  position: relative;
  padding-left: 1.2rem;
}

h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 70%;
  background: #0066cc;
  border-radius: 2px;
}

.table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  position: relative;
}

.table th,
.table td {
  padding: 1.2rem;
  text-align: left;
  font-size: 0.95rem;
}

.table th {
  background: linear-gradient(135deg, #0066cc 0%, #004799 100%);
  color: white;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.table tr:not(:last-child) td {
  border-bottom: 1px solid #f0f2f5;
}

.table tr:hover td {
  background: #f8faff;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 1.5rem;
  box-shadow: 0 4px 8px rgba(0,0,0,0.08);
}

.product-name {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 0.5rem;
}

.product-desc {
  color: #7f8c9d;
  font-size: 0.9rem;
  line-height: 1.4;
  margin-bottom: 0.5rem;
}

.product-price {
  color: #00a854;
  font-weight: 600;
  font-size: 1.1rem;
}

.btn {
  padding: 0.6rem 1.2rem;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
}

.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0,51,102,0.15);
}

.btn:active {
  transform: translateY(0);
}

.handle-btn {
  background: linear-gradient(135deg, #00c853 0%, #009624 100%);
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0,0,0,0.4);
  backdrop-filter: blur(4px);
  z-index: 1000;
}

/* 弹窗内容优化 */
.modal-body {
  padding: 1rem 0;
}

.detail-item {
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: #f8f9fc;
  border-radius: 8px;
  border: 1px solid #e0e4e9;
}

.detail-item strong {
  color: #2c3e50;
  font-weight: 600;
}

.application-detail {
  margin-top: 0.5rem;
  padding: 0.8rem;
  background: white;
  border-radius: 6px;
  border: 1px solid #e0e4e9;
  font-size: 0.95rem;
  line-height: 1.5;
  color: #555;
}

.modal-content {
  background: white;
  border-radius: 1.2rem;
  padding: 2rem;
  width: 600px;
  max-width: 95%;
  max-height: 90vh;  /* 新增最大高度限制 */
  overflow-y: auto;  /* 添加滚动支持 */
  position: relative;
  animation: modalIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  /* 新增居中定位保障 */
  margin: auto;
  top: auto;
  left: auto;
  transform: none;
}

@keyframes modalIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-title {
  color: #2c3e50;
  font-size: 1.4rem;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 2px solid #f0f2f5;
}

.detail-item {
  display: grid;
  grid-template-columns: 100px 1fr;
  gap: 1rem;
  margin-bottom: 1rem;
  padding: 0.8rem;
  background: #f8f9fc;
  border-radius: 8px;
}

.image-proof-grid {
  display: flex; /* 使用弹性布局 */
  justify-content: flex-start; /* 图片靠左排列 */
  align-items: center;
  flex-wrap: nowrap; /* 确保图片在一行 */
  gap: 10px; /* 图片之间的间距 */
  overflow-x: auto; /* 允许超出时滚动 */
  padding: 10px 0;
}

.image-proof-item {
  flex: 1; /* 让图片自适应容器宽度 */
  max-width: 30%; /* 每张图片最大宽度，保证三张图片并排 */
  min-width: 100px; /* 最小宽度，防止过小 */
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.image-proof-item:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.proof-image {
  width: 100%;
  height: auto;
  object-fit: cover; /* 保持图片比例，填充容器 */
  border-radius: 8px;
}


.close-btn {
  background: #f0f2f5;
  color: #7f8c9d;
}

.close-btn:hover {
  background: #e4e7ec;
}

.select {
  border: 1px solid #e0e4e9;
  border-radius: 8px;
  padding: 0.8rem;
  width: 100%;
  appearance: none;
  background: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%230066cc'%3e%3cpath d='M7 10l5 5 5-5z'/%3e%3c/svg%3e") no-repeat right 0.8rem center/16px 16px;
}


/* 响应式优化 */
@media (max-width: 768px) {
  .segmented-control {
    margin: 0 1rem; /* 移动端边距缩小 */
  }

  .segmented-btn {
    padding: 0.8rem;
    font-size: 0.9rem;
  }
  .after-sales {
    margin: 1rem;
    padding: 1.5rem;
  }

  .product-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .product-image {
    margin-bottom: 1rem;
  }

  .image-proof-grid {
    grid-template-columns: 1fr; /* 移动端单列布局 */
  }

  .image-proof-item {
    padding-top: 56.25%; /* 16:9 比例 */
  }

  .modal-content {
    padding: 1.5rem;
  }

  .detail-item {
    padding: 0.8rem;
  }
}
</style>
